<?php
/**
 * Created by PhpStorm.
 * User: yys
 * Date: 2016/11/14
 * Time: 14:39
 */

namespace App\Services\Tool\ImageProcessor;


use App\Services\ImgServices\ImgTool;
use Illuminate\Support\Facades\Log;

class ImagickTool
{

    public function __construct()
    {
    }
    /**
     * 图片保存到本地
     * @param $file
     * @param int $path
     * @return array
     *
     */
    public function save($file)
    {
        try{
        if ($file != null) {
            //获取图片格式
            $extension = $this->getImageExt($file);
            if(!$extension) return "";
//            父级文件夹
            $folder=date('Ym');
//            文件夹绝对路径
            $folder_path=public_path("images/".$folder );
            @$this->mkFolder($folder_path);
            //生成图片名
            $newName = md5(date('ymdhis').rand(1, 1000)) . "." . $extension;
            $file->move($folder_path,$newName);
            $file_absolute_path=$folder_path.DIRECTORY_SEPARATOR.$newName;
            if(file_exists($file_absolute_path)){
                $file_md5=md5_file($file_absolute_path);
                $md5_file_name=$folder.DIRECTORY_SEPARATOR.$file_md5."." . $extension;
                $md5_file_absolute_path=public_path("images/".$md5_file_name );
                rename($file_absolute_path,$md5_file_absolute_path);
                return $md5_file_name;
            }
            return $folder.DIRECTORY_SEPARATOR.$newName;
        } else {
            return "";
        }
        }catch (\Exception $e){
            Log::info($e);
            return "";
        }
    }

    /****
     * svg内容生成svg文件
     * @param $svg_content
     * @return string
     */
    public function svgContents2SvgFile($svg_content)
    {
        try{
            $svg_content=trim($svg_content);
            if(empty($svg_content)) return '';
                  //            父级文件夹
                $folder=date('Ym');
                 //            文件夹绝对路径
                $folder_path=public_path("images/svg/".$folder );
                @$this->mkFolder($folder_path);
                //生成图片名
                $svg_name = md5(date('ymdhis').rand(1, 1000)) . ".svg";
                $svg_absolute_path=$folder_path.DIRECTORY_SEPARATOR.$svg_name;
                file_put_contents($svg_absolute_path, $svg_content);
                return 'svg'.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$svg_name;
        }catch (\Exception $e){
            Log::info($e);
            return "";
        }
    }
    /***
     * 获取图片格式扩展
     * @param $file_name
     * @return bool|string
     */
    public static function getImgExtByStateFunFileName($file_name){
    try{
        if(!is_file($file_name)){
            return '';
        }
        $file=file($file_name);
        if(!empty($file)){
            return self::getImageExtByStateFun($file);
        }
        return '';
    }catch (\Exception $e){
        Log::info( $e);
        return '';
    }
    }
    /**
     * 创建文件夹
     * @param $path
     */
    function mkFolder($path)
    {
        if(!is_readable($path))
        {
            is_file($path) or mkdir($path,0777);
        }
    }

    /**
     * 获取图片的格式
     * @param $file
     * @return bool|string
     */
    function getImageExt($file)
    {
        $image_mime = image_type_to_mime_type(exif_imagetype($file));
        switch ($image_mime) {
            case "image/gif":
                return 'gif';
                break;
            case "image/jpeg":
                return 'jpg';
                break;
            case "image/png":
                return 'png';
                break;
            case "image/bmp":
                return 'bmp';
                break;
        }
        return false;
    }
    public static function getImageExtByStateFun($file)
    {
        $image_mime = image_type_to_mime_type(exif_imagetype($file));
        switch ($image_mime) {
            case "image/gif":
                return 'gif';
                break;
            case "image/jpeg":
                return 'jpg';
                break;
            case "image/png":
                return 'png';
                break;
            case "image/bmp":
                return 'bmp';
                break;
        }
        return false;
    }
    /**
     * 判断图片的完整性
     * @param $file_path
     * @return bool|string
     */
    function judgeImageIsComplete($file_path)
    {
        if(!file_exists($file_path)){
            return false;
        }
        $image_mime = image_type_to_mime_type(exif_imagetype($file_path));
        switch ($image_mime) {
            case "image/gif":
                return @imagecreatefromgif($file_path);
                break;
            case "image/jpeg":
                return @imagecreatefromjpeg($file_path);
                break;
            case "image/png":
                return @imagecreatefrompng($file_path);
                break;
            default:
                return false;
                break;
        }
        return false;
    }
    /**
     * 获取图片大小，单位kb
     * @param $img_path
     * @return float|int
     */
    public function getImageSize($img_path)
    {
        if(!is_file($img_path)){
            return 0;
        }
        return filesize($img_path)/1000;
    }
    public static function getImagePath($path)
    {
        return asset('images/'. $path);
    }
    public static function getImageJpgPath($path)
    {
        return asset('image/'. $path);
    }
    public static function getThumbnailPath($path)
    {
        return asset('thumbnail/'. $path);
    }

    /***
     * @param $img_path
     * @param int $width
     * @param int $height
     * @param bool $same_name ture原图和缩略图文件名相同 false 文件名不同
     * @return string
     */
    public function img2thumbbywidthandheight($img_path,$width = 300, $height = 300,$same_name=true){
        try{
            $img_absolute_path=public_path()."/images/".$img_path;
            if($same_name){
                $thumb_path=$img_path;
            }else{
                $img_data=explode(".",$img_path);
                $random=rand(1,100);
                $thumb_path=$img_data[0].$random.'.'.$img_data[1];
            }
            $thumb_absolute_path=public_path(). "/thumbnail/"  .$thumb_path;
            $folder_path=dirname($thumb_path);
            @$this->mkFolder($folder_path);
            $img_thumb=new Imagick($img_absolute_path,$thumb_absolute_path);
            $img_thumb->stripImage();
            $img_thumb->thumbnail($width,$height);
            $img_thumb->saveTo($thumb_absolute_path);
            $img_thumb->destroy();
            return $thumb_path;
        }catch (\Exception $e){
            Log::info($e);
            return '';
        }
    }
    public function img2ThumbByImgPath($img_path,$width = 300, $height = 300,$quality_compression=true){
        try{
            $img_absolute_path=public_path().DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR.$img_path;
            if(!file_exists($img_absolute_path)){
                return '';
            }
            $folder=date('Ym');
            // 文件夹绝对路径
            $folder_path=public_path("images/".$folder );
            @$this->mkFolder($folder_path);
            //生成图片名
            $extension = $this->getImageExt($img_absolute_path);
            $newName = md5(date('ymdhis').rand(1, 1000)) . "." . $extension;
            $thumb_absolute_path=$folder_path.DIRECTORY_SEPARATOR.$newName;
            $img_thumb=new Imagick($img_absolute_path,'');
            $img_thumb->stripImage();
            $img_thumb->thumbnail($width,$height);
            $img_thumb->saveTo($thumb_absolute_path);
            $img_thumb->destroy();
            $thumb_path=$folder.DIRECTORY_SEPARATOR.$newName;
            if(file_exists($thumb_absolute_path)){
                if($quality_compression){
                    //图片质量压缩
                    $quality_compression_img_path=ImgTool::pngquantImgCompression($thumb_absolute_path);
                }
                if(isset($quality_compression_img_path)&&!empty($quality_compression_img_path)){
                    $quality_compression_img_absolute_path=public_path("images/".$quality_compression_img_path);
                    $file_md5=md5_file($quality_compression_img_absolute_path);
                    $thumb_absolute_path=$quality_compression_img_absolute_path;
                }else{
                    $file_md5=md5_file($thumb_absolute_path);
                }
                $img=ImgTool::getImgObjInDBByMd5($file_md5);
                if(!empty($img)){
                    $thumb_path=$img->img_in_url;
                }else{
                    $md5_file_name=$folder.DIRECTORY_SEPARATOR.$file_md5."." . $extension;
                    $md5_file_absolute_path=public_path("images/".$md5_file_name);
                    rename($thumb_absolute_path,$md5_file_absolute_path);
                    $thumb_path=$md5_file_name;
                }
                return $thumb_path;
            }
            return $thumb_path;
        }catch (\Exception $e){
            Log::info($e);
            return '';
        }
    }
    /***
     * 获取图片参数
     * @param $img_path
     * @return array
     */
    public function getImgParameter($img_path){
        try{
            $img_thumb=new Imagick($img_path);
            $parameter=array();
            $imageResolution = $img_thumb->getImageResolution();
            $parameter['img_h']=$img_thumb->getImageHeight();
            $parameter['img_w']=$img_thumb->getImageWidth();
            $parameter['dpi_y']= $imageResolution['y'];
            $parameter['dpi_x']=$imageResolution['x'];
            return $parameter;
        }catch (\Exception $e){
            Log::info($e);
            return array();
        }
    }

    /***
     * 获取图片宽高和Md5值
     * @param $img_path
     * @return array
     */
    public static function getImgParamByStateFuncAndImgPath($img_path){
        try{
            if(!file_exists($img_path)){
                return array();
            }
            $img_thumb=new Imagick($img_path);
            $parameter=array();
            $parameter['height']=$img_thumb->getImageHeight();
            $parameter['width']=$img_thumb->getImageWidth();
            $parameter['md5']=md5_file($img_path);
            $img_thumb->destory();
            return $parameter;
        }catch (\Exception $e){
            Log::info($e);
            return array();
        }
    }
    public function getImageWidth($image){
        $img=new Imagick($image);
        return $img->getImageWidth();
    }
    public function getImageHeight($image){
        $img=new Imagick($image);
        return $img->getImageHeight();
    }

    /***
     * 图片背景转换成透明色
     * @param $img_path  原图位置
     * @param $save_path 保存转换成图片位置
     * @return bool
     */
    public function setImgBackgroundToTransparent($img_path,$save_path){
        try{
            if(!file_exists($img_path)){
                return false;
            }
            $image = new \Imagick($img_path);
            $image->borderImage(new \ImagickPixel("white"),1,1);
            $image->paintfloodfillimage('transparent',2000,NULL,0,0);
            $draw = new \ImagickDraw();
            $draw->color(0,0,\Imagick::PAINT_FLOODFILL);
            $image->drawImage($draw);
            $image->shaveImage(1,1);
            $image->writeImage($save_path);
            $image->clear();
            $image->destroy();
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 修改svg图片大小,透明背景
     * @param $svg_path    svg文件路径
     * @param int $width   宽
     * @param int $height  高
     * @param int $dpi_x   dpi
     * @param int $dpi_y
     * @return bool
     */
    function resizeSvgAndReturnPng($svg_path,$width=100, $height=100,$dpi_x=180,$dpi_y=180)
    {
        try {
            if(!file_exists($svg_path)){
                return false;
            }
            //            文件夹绝对路径
            $file_path="svg".DIRECTORY_SEPARATOR.date('Ym');
            $folder_path=public_path().DIRECTORY_SEPARATOR. "images".DIRECTORY_SEPARATOR.$file_path;
            @$this->mkFolder($folder_path);
            //生成图片名
            $newName = md5(date('ymdhis').rand(1, 1000)) . ".png";
            $svg_png_absolute_path=$folder_path.DIRECTORY_SEPARATOR.$newName;
            $im = new \Imagick();
            $svgdata = file_get_contents($svg_path);
             //设置图片图透明背景
            $im->setBackgroundColor(new \ImagickPixel('transparent'));
            $im->readImageBlob($svgdata);
            $im->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1);
            //设置图片DPI
            $im->setImageResolution($dpi_x, $dpi_y);
            $im->setImageUnits(\Imagick::RESOLUTION_PIXELSPERINCH);
            $im->setImageFormat("png24");
            $im->writeImage($svg_png_absolute_path);
            $im->clear();
            $im->destroy();
            return $file_path.'/'.$newName;
        } catch(\Exception $e) {
            Log::info($e);
            return false;
        }
    }
    /***
     * svg文件转换成png图片
     * @param $svg_path
     * @return bool|string
     */
    public function svg2Png($svg_path,$dpi_x=72,$dpi_y=72){
        $svg_contents='';
        try{
            if(!file_exists($svg_path)){
                return '';
            }
            $file_path="svg".DIRECTORY_SEPARATOR.date('Ym');
            $folder_path=public_path().DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR.$file_path;
            @$this->mkFolder($folder_path);
            //生成图片名
            $svg_png_name = md5(date('ymdhis').rand(1, 1000)) . ".png";
            $svg_png_absolute_path=$folder_path.DIRECTORY_SEPARATOR.$svg_png_name;
            $svg = file_get_contents($svg_path);
            $svg_contents=$svg;
            $im = new \Imagick();
            $im->setBackgroundColor(new \ImagickPixel('transparent'));
            $im->readImageBlob($svg);
            $im->setImageResolution($dpi_x, $dpi_y);
            $im->setImageUnits(\Imagick::RESOLUTION_PIXELSPERINCH);
            if($dpi_x==180){
                $im->setImageFormat("png24");
            }else{
                $im->setImageFormat("png8");
            }
            $im->writeImage($svg_png_absolute_path);
            $im->clear();
            $im->destroy();
            return $file_path.DIRECTORY_SEPARATOR.$svg_png_name;
        }catch (\Exception $e){
            Log::info($e);
            Log::info($svg_contents);
            return '';
        }
    }
    /***
     * 修改svg宽高
     * @param $svg
     * @param $minWidth
     * @param $minHeight
     * @return bool|mixed
     */
    function svgScaleHack($svg, $minWidth, $minHeight)
    {
        try{
            $reW = '/(.*<svg[^>]* width=")([\d.]+px)(.*)/si';
            $reH = '/(.*<svg[^>]* height=")([\d.]+px)(.*)/si';
            preg_match($reW, $svg, $mw);
            preg_match($reH, $svg, $mh);
            if(sizeof($mw)<3||sizeof($mw)<3){
                Log::info('svg更改大小失败');
                return false;
            }
            $width = floatval($mw[2]);
            $height = floatval($mh[2]);
            if (!$width || !$height) return false;
            $scale = 1;
            if ($width < $minWidth)
                $scale = $minWidth/$width;
            if ($height < $minHeight)
                $scale = max($scale, ($minHeight/$height));

            $width *= $scale*2;
            $height *= $scale*2;

            $svg = preg_replace($reW, "\${1}{$width}px\${3}", $svg);
            $svg = preg_replace($reH, "\${1}{$height}px\${3}", $svg);
            return $svg;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    /***
     * 生成遮罩图片
     * @param $img_path        底图绝对地址
     * @param int $img_width   底图宽
     * @param int $img_height  底图高
     * @param $mask_path       遮罩层绝对地址
     * @param int $mask_width  遮罩层宽
     * @param int $mask_height 遮罩层高
     * @param int $path        images下文件夹
     * @param int $x           相对图像顶点左上位置（0,0）的横坐标
     * @param int $y           相对图像顶点左上位置（0,0）的纵坐标
     * @return bool|string     生成失败返回false，成功返回图片相对public_path('images/')位置
     */
    public function generateMaskImg($img_path,$img_width=1000,$img_height=1000,$mask_path,$mask_width=1000,$mask_height=1000,$path=1,$x=0 ,$y=0){
        try{
            if(!file_exists($img_path)||!file_exists($mask_path)){
                return false;
            }
            $newName = $path.'/'.md5(date('ymdhis').rand(1, 1000)) . ".png";
            $dude = new \Imagick($img_path);
            $mask = new \Imagick($mask_path);
            $mask->resizeImage($img_width,$img_height,\Imagick::FILTER_LANCZOS,1);
            $dude->resizeImage($mask_width,$mask_height,\Imagick::FILTER_LANCZOS,1);
            $dude->setImageMatte(1);
            $dude->compositeImage($mask, \Imagick::COMPOSITE_DSTIN, $x, $y);
            $dude->setImageFormat("png");
            $dude->writeImage(public_path('images/').$newName);
            return $newName;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }

    /***
     * 生成遮罩层
     * @param $img_path
     * @param $img_w
     * @param $img_h
     * @param $mask_path
     * @param int $mask_width
     * @param int $mask_height
     * @param $maskCenterPointOffsetX
     * @param $maskCenterPointOffsetY
     * @param $maskPositonX
     * @param $maskPositonY
     * @param $multiple
     * @param int $dpi
     * @return bool|string
     */
    public static function generateMaskImg2($img_path,$img_w,$img_h,$mask_path,$mask_width=1000,$mask_height=1000,
                                            $maskCenterPointOffsetX ,$maskCenterPointOffsetY,$maskPositonX,$maskPositonY,$multiple,$dpi=180){
        try{
            if(!file_exists($img_path)||!file_exists($mask_path)){
                return false;
            }
            $newName = md5(date('ymdhis').rand(1, 1000)) . ".png";
            //需要处理图片
            $image=new Imagick($img_path);
            $image->setImageResolution($dpi,$dpi);
            $image->resize($img_w,$img_h,'force');
            $mask_bg = new Imagick();
            //遮罩模板图
            $mask_image = new Imagick($mask_path);
            $mask_image->setImageResolution($dpi,$dpi);
            $mask_image->resize($mask_width,$mask_height,'force');
            $color_transparent = new \ImagickPixel('transparent'); //transparent 透明色
            //水印底图
            $mask_bg = $mask_bg->newImage($image->getImageWidth(),$image->getImageHeight(),$color_transparent,'png');
            $mask_bg->addWatermarkFromImage(
                $mask_image,
                $maskCenterPointOffsetX-($maskCenterPointOffsetX+$mask_image->getImageWidth()/2-$maskPositonX),
                $maskCenterPointOffsetY-($maskCenterPointOffsetY+$mask_image->getImageHeight()/2-$maskPositonY)
            );
            $image->getImagick()->setImageMatte(1);
            $image->getImagick()->compositeImage($mask_bg->getImagick(), \Imagick::COMPOSITE_DSTIN, 0, 0);
            $image->saveTo(public_path('images/mask/'.$newName));
            $image->destroy();
            $mask_bg->destroy();
            $mask_image->destroy();
            return 'mask/'.$newName;
        }catch (\Exception $e){
            Log::info($e);
            return false;
        }
    }
    public static function only_no()
    {
        return date('YmdHis') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }
    /***
     * 获取图片参数
     * @param $img_path
     * @return array
     */
    public function getImgParam($img_path){
        if(!file_exists($img_path)){
            return array();
        }
        $img=new Imagick($img_path);
        $data['width']=$img->getImageWidth();
        $data['height']=$img->getImageHeight();
        $data['md5']=md5_file($img_path);
        $img->destory();
        return $data;
    }

    /***
     * 获取文件md5值
     * @param $file_path
     * @return string
     */
    public static function getFileMd5ByFilePath($file_path){
        try{
        if(!file_exists($file_path)){
            return '';
        }
        return md5_file($file_path);
        }catch (\Exception $e){
            Log::info($e);
            return '';
        }
    }
}
